package com.yuji.aacar.widgets.canceledit;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.yuji.aacar.R;
import com.yuji.aacar.tools.Tools;


/**
 * <li>Date: 2017/7/19
 * <li>Description:当有字时会出现x按钮的edit
 */
public class CancelEditText extends AppCompatEditText {
    private boolean isClick;
    private int left;
    private int top;
    private int right;
    private int bottom;

    public CancelEditText(Context context) {
        super(context);
        init();
    }

    public CancelEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CancelEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(!TextUtils.isEmpty(getText())) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.mipmap.cancel);
            int marginRight = Tools.getPercentSize(getContext(), 38, true);
            left=getWidth() - bitmapDrawable.getMinimumWidth() - marginRight;
            top=(getHeight() - bitmapDrawable.getMinimumHeight()) / 2;
            right=getWidth() - marginRight;
            bottom=(getHeight() - bitmapDrawable.getMinimumHeight()) / 2 + bitmapDrawable.getMinimumHeight();
            bitmapDrawable.setBounds(left, top,right ,bottom) ;
            bitmapDrawable.draw(canvas);
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                isClick=isInArea(event.getX(),event.getY());
                break;
            case MotionEvent.ACTION_UP:
                if(isClick&&isInArea(event.getX(),event.getY())) {
                    setText("");
                }

                break;
        }
        return super.onTouchEvent(event);
    }

    private boolean isInArea (float x,float y){
        if(x>=left-40&&x<=right+40&&y>=0&&y<=getHeight()){
            return true;
        }else {
            return false;
        }
    }
}
